class ChatSessionController < ApplicationController
  layout "main"
  def index
    @chat_sessions= ChatSession.all :conditions=>["stop > ?", Time.now.utc], :order=>"start"
  end
  def destroy
    @chat_sessions= ChatSession.find params[:id]
    @chat_sessions.destroy
    redirect_to :action => "index"
  end
  def new
    @chat_session= ChatSession.new :start=>Time.now, :stop=>(2.hours.from_now)
    @courses= Course.all
  end
  def create
    @chat_session= ChatSession.new params[:chat_session]
    @courses= Course.all
    #check conflict
    @conflict= false
    chat_sessions= ChatSession.all :conditions=>["stop > ?", Time.now.utc]
    chat_sessions.each do |s|
      if @chat_session[:start] > s[:start] and @chat_session[:start] < s[:stop]
        @conflict= true
        @session_conflict = s
        break
      end
    end
    if @conflict
      flash[:notice]= "ขออภัย เวลาที่ท่านต้องการใช้ตรงกับ #{@session_conflict.name} กรุณาเลือกเวลาอื่น"
      render :action => "new"
    else
      @chat_session.save
      user_group= params[:user_group].map(&:to_i)
      if user_group.include?(0)
        users= Log.all :select=>"DISTINCT user_id"
      else
        users= Log.all :conditions=>{:course_id=>user_group}, :select=>"DISTINCT user_id"
      end
      users.each do |user|
        ChatParticipant.create :chat_session_id=>@chat_session.id, :user_id=>user.attributes['user_id'].to_i
      end
      flash[:notice]= "จองห้องสนทนาเรียบร้อยแล้ว"
      redirect_to :action => "index"
    end
  end
end
